import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Button, Image, ScrollView} from '@tarojs/components';
import {AtActionSheet, AtActionSheetItem, AtActivityIndicator} from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import {store2Props} from '../../selectors';
import {OSS_PATH_PREFIX, OSS_BASE_PATH_PREFIX, TASK_TYPE_TIMES_NAMES, CODE_SUCCESS} from '../../constant';
type IInfoProps = T.IProps & T.IInfoProps;
import PageLoading from '../../../../common/PageLoading';
import CustomScrollView from '@/common/scrollview';

import './TaskModal.less';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/flex.scss';
// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 游戏任务模态框
 */
export default class TaskModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      ActionSheet: {
        title: '做任务领取奖励',
        extraTitle: '您当前的剩余魔力币：',
      },

      pics: {
        icon: OSS_PATH_PREFIX + '/gameTaskIcon.png',
        titleLeft: OSS_PATH_PREFIX + '/taskTitleLeft.png',
        titleRight: OSS_PATH_PREFIX + '/taskTitleRight.png',
        modalCloseIcon: OSS_PATH_PREFIX + '/taskClose.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/empty.png',
      },
      loading: {
        status: false,
        text: '',
        style: {},
      },
      empty: {
        text: '玩法升级中',
      },

      // 不同奖励不同显示内容
      renderPrizeContent: [
        'renderGameTimes',
        'renderMeanValue',
        'renderMeanCoins',
        'renderProp',
        'renderSyntheticCard',
      ],

      // 错误图片记录
      imageError: {},

      refresherTriggered: false,
    };
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    // 点击完成
    if (nextProps.main.status.loadingTaskDetail == false && this.props.main.status.loadingTaskDetail == true) {
      // 成功则跳转
      let code = nextProps.main.response.loadTaskDetail;
      if (code == CODE_SUCCESS) {
        let detail = nextProps.main.task.detail;

        let gameTaskReleaseVO = detail.gameTaskReleaseVO;
        let gameTaskInfoVO = detail.gameTaskInfoVO;

        Taro.redirectTo({
          url:
            gameTaskReleaseVO.pagePath +
            '?taskId=' +
            detail.id +
            '&taskConditionsType=' +
            gameTaskInfoVO.conditionsType,
        });
      } else {
        Taro.showToast({
          title: '操作失败',
          icon: 'none',
        });
      }
    }
    if (nextProps.main.status.loadingTask == false && this.props.main.status.loadingTask == true) {
      this.setState({
        refresherTriggered: false,
      });
    }
  }

  /**
   * 点击取消
   */
  handleCancel = () => {
    console.log('taskModal 蒙层取消');
    this.props.onCancel();
  };

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      main: {
        task: {items},
        status: {loadingTask},
      },
      visible,
      actions: {action},
      navbarSettings
    } = this.props;
    console.log('taskModal render loadingTask', loadingTask);

    return (
      <AtActionSheet isOpened={visible} className="taskModal" onClose={this.handleCancel} atActionSheetStyle={{top: navbarSettings.navBarHeight}}>
        {this.renderTitle()}
        {this.renderListContent(items)}
      </AtActionSheet>
    );
  }

  /**
   *
   * @returns
   */
  renderLoadingContent() {
    const {
      loading: {status, text, style},
    } = this.state;
    return (
      <View className="loadingContent">
        <PageLoading style={style} />
      </View>
    );
  }
  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 渲染列表
   * @returns
   */
  renderListContent(items) {
    let {
      main: {
        task,
        status: {loadingTask},
      },
      actions: {action},
    } = this.props;
    const {
      pics,
      loading: {status},
      renderPrizeContent,
      refresherTriggered,
    } = this.state;
    console.log('taskmodal renderlistconten taskitems', items);

    return (
      <CustomScrollView
        scrollY
        scrollWithAnimation
        onRefresherRefresh={this.handleRreshList}
        onScrollToLower={this.handleScrollLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
        refresherBackground="#747EF6"
        className="taskScrollView"
      >
        {items.length > 0 ? (
          <View className="taskModalContent">
            {items.map((i: any, index: number) => (
              <View key={index} className="at-row item">
                {i.taskCycle ? <View className="timeLimit">限时</View> : <></>}
                <View className="at-col at-col-2 left">
                  <Image
                    src={i.taskLogo || pics.icon}
                    className="taskIcon"
                    onError={(e) =>
                      this.handleImageError(e, index, {
                        propName: 'task',
                        extraName: 'items',
                        imageState: 'taskLogo',
                      })
                    }
                  />
                </View>
                <View className="at-col at-col-7 middle">
                  <View className="taskName">
                    <View className="taskTitle">{i.taskName}</View>
                    <View>{`(${i.completedTimes || 0}/${i.sumTimes || 0})`}</View>
                  </View>
                  <View className="extraTitle">
                    <View>奖励:</View>
                    {this[renderPrizeContent[i.rewardType]](i)}
                  </View>
                </View>
                <View className="at-col at-col-3 right">
                  {i.completedTimes > 0 && i.sumTimes > 0 && i.completedTimes == i.sumTimes ? (
                    <Button className="disableBtn">已完成</Button>
                  ) : (
                    <Button className="finishBtn" onClick={() => this.handleFinish(i)}>
                      去完成
                    </Button>
                  )}
                </View>
              </View>
            ))}
          </View>
        ) : (
          this.renderEmptyContent()
        )}
      </CustomScrollView>
    );
  }

  /**
   * 去完成
   */
  handleFinish = (item) => {
    console.log('taskModal handleFinish item', item);
    this.props.actions.action.loadTaskDetailById({id: item.id});
  };

  /**
   * 图片加载错误  通用
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState, extraName} = item;

    let {imageError, pics} = this.state;

    if (imageError[propName + '_' + extraName]) {
      imageError[propName + '_' + extraName] = imageError[propName + '_' + extraName].concat([index]);
    } else {
      imageError[propName + '_' + extraName] = [index];
    }
    console.log('imageError', imageError);

    let result = JSON.parse(JSON.stringify(main[propName][extraName]));
    let currentImage = imageError[propName + '_' + extraName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: pics.icon,
      };
    });

    this.props.actions.action.commonChange('main.' + propName + '.' + extraName, result);
  };

  /**
   * 拉倒底部
   */
  handleScrollLower = () => {
    console.log('taskModal handleScrollLower 拉倒底部');
    const {
      main: {
        task: {page, items},
      },
    } = this.props;
    let params = {
      ...page,
      pageNum: page.pageNum + 1,
    };
    if (params.pageNum > 0 && items.length == page.total) {
      return;
    }
    // this.props.onQueryTask(params);
  };

  /**
   * 下拉刷新列表
   */
  handleRreshList = () => {
    const {
      main: {
        task: {
          page: {pageSize},
        },
      },
    } = this.props;

    const {refresherTriggered} = this.state;
    if (refresherTriggered) return;

    this.setState({
      refresherTriggered: true,
    });

    this.props.onQueryTask({
      pageSize,
      pageNum: 0,
      total: 0,
    });
  };

  /**
   * 渲染标题行
   */
  renderTitle() {
    const {pics, ActionSheet} = this.state;
    const {
      main: {userInfo},
    } = this.props;

    return (
      <View className="taskModalHeader">
        <View className="tModalTitle">
          <Image src={pics.titleLeft} className="taskLeftIcon" />
          <View className="tTitle">{ActionSheet.title}</View>
          <Image src={pics.titleRight} className="taskRightIcon" />
        </View>
        <Image src={pics.modalCloseIcon} className="taskModalClose" onClick={this.handleCancel} />
        <View className="tModalExtra">{`${ActionSheet.extraTitle}${userInfo.magicCoin || 0}个`}</View>
      </View>
    );
  }

  /**
   * 渲染游戏次数
   * @returns
   */
  renderGameTimes(data) {
    console.log('taskModal renderGameTimes data', data);
    return (
      <View className="gameTimes">
        <View>游戏次数+{data.rewardValue}</View>
        {data.rewardGameType != null ? <View>({TASK_TYPE_TIMES_NAMES[Number(data.rewardGameType)]}专属)</View> : <></>}
      </View>
    );
  }

  /**
   * 渲染魔力值
   * @returns
   */
  renderMeanValue(data) {
    return (
      <View className="meanValue">
        <View>魔力值</View>
        <View>+{data.rewardValue}</View>
      </View>
    );
  }

  /**
   * 渲染魔力币
   * @returns
   */
  renderMeanCoins(data) {
    return (
      <View className="meanCoin">
        <View>魔力币</View>
        <View>+{data.rewardValue}</View>
      </View>
    );
  }

  /**
   * 渲染道具
   * @returns
   */
  renderProp(data) {
    return (
      <View className="prop">
        <View>{data.rewardName}+1</View>
      </View>
    );
  }

  /**
   * 渲染卡片
   * @returns
   */
  renderSyntheticCard(data) {
    return (
      <View className="syntheticCard">
        <View>({data.rewardName})+1</View>
      </View>
    );
  }
}
